<template>
  <div class="container">
    <el-card>
      <h4 class="question-new-top">试题录入</h4>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学科" prop="subjectID">
          <el-select @change="getDirectorys" v-model="form.subjectID" placeholder="请选择">
            <el-option
              v-for="item in subject"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录"  prop="catalogID">
          <el-select v-model="form.catalogID" placeholder="请选择">
            <el-option
              v-for="item in directorys"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业" prop="enterpriseID">
          <el-select v-model="form.enterpriseID" placeholder="请选择">
            <el-option
              v-for="item in companys"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select @change="onProvinceChange" v-model="form.province" placeholder="请选择">
            <el-option
              v-for="item in provincesCity"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
          <el-select v-model="form.city" placeholder="请选择">
            <el-option
              v-for="item in citys"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向" prop="direction">
          <el-select v-model="form.direction" placeholder="请选择">
            <el-option
              v-for="item in constantsList"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型" prop="questionType">
          <el-radio-group @change="typeChange" v-model="form.questionType">
            <el-radio v-model="form.questionType" label="1">单选</el-radio>
            <el-radio v-model="form.questionType" label="2">多选</el-radio>
            <el-radio v-model="form.questionType" label="3">简答</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度"  prop="difficulty">
          <el-radio v-model="form.difficulty" label="1">简单</el-radio>
          <el-radio v-model="form.difficulty" label="2">一般</el-radio>
          <el-radio v-model="form.difficulty" label="3">困难</el-radio>
        </el-form-item>
        <el-form-item label="题干"> <quillEditor ref="myQuillEditor1" v-model="form.question"  :options="editorOption"/> </el-form-item>
        <el-form-item label="选项"  v-show="form.questionType !== '3'">
          <!-- 单选 -->
          <div v-show="form.questionType === '1'">
            <el-checkbox-group  v-model="checkList">
                <div v-for="(item, index) in form.options" :key="item.code" style="display: flex">
                <el-radio v-model="render" :label="item.code">{{ item.code }}：</el-radio>
                <el-input v-model="item.title" style="width:240px"></el-input>
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  :http-request="onRequest"
                  :show-file-list="false"
                  @click.native="checkedIndex = index">
                  <i v-if="!item.img" class="el-icon-plus avatar-uploader-icon" ></i>
                  <span v-if="!item.img"></span>
                  <img v-else :src="item.img" alt="">
                </el-upload>
              </div>
              </el-checkbox-group>
              <el-button type="danger" disabled>+增加选项和答案</el-button>
          </div>
          <!-- 多选 -->
          <div v-show="form.questionType === '2'">
              <el-checkbox-group v-model="checkBoxList">
                <div v-for="(item, index) in form.options" :key="item.code" style="display: flex">
                  <el-checkbox :checked="item.isRight === 1" @change="boxChange($event,index)" :label="item.code" >{{ item.code }} ： </el-checkbox>
                  <el-input v-model="item.title" style="width: 400px" />
                  <el-upload
                  class="avatar-uploader"
                  action="#"
                  :http-request="onRequest"
                  :show-file-list="false"
                  @click.native="checkedIndex = index">
                  <i v-if="!item.img" class="el-icon-plus avatar-uploader-icon" />
                  <img v-else :src="item.img" alt="" >
                </el-upload>
                </div>
              </el-checkbox-group>
              <el-button type="danger" @click="addBtn">+增加选项和答案</el-button>
          </div>
        </el-form-item>
        <el-form-item label="解析视频">
          <el-input v-model="form.videoURL"></el-input>
        </el-form-item>
        <el-form-item label="答案解析"  prop="answer"> <quillEditor ref="myQuillEditor" v-model="form.answer" :options="editorOption"/> </el-form-item>
        <el-form-item label="题目备注">
          <el-input v-model="form.remarks" :rows="4" style="width: 400px" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="试题标签">
          <el-select multiple v-model="form.tags" placeholder="请选择">
            <el-option
              v-for="item in tags"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import hljs from 'highlight.js'
import 'highlight.js/styles/monokai-sublime.css'
import * as SubApi from '@/api/hmmm/subjects'
import { simple } from '@/api/hmmm/directorys'
import { add, detail, update } from '@/api/hmmm/questions'
import { list } from '@/api/hmmm/companys'
import { Message } from 'element-ui'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction } from '@/api/hmmm/constants'
import { tagsSimple } from '@/api/hmmm/tags'
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDLUN5WgZCZgW5NDm47uQfdKmwpRmqc7NN',
  SecretKey: 'kDPKxJOCjywd3C3ey0lFSO3RYOwDDwOZ'
})
hljs.configure({
  languages: ['javascript', 'python']
})
export default {
  name: 'questionsNew',
  components: {
    quillEditor
  },
  data () {
    return {
      queryId: this.$route.query.id || null,
      subject: [],
      directorys: [],
      number: '',
      companys: [],
      provinces: [],
      citys: [],
      render: 'A',
      tags: [],
      difficulty: 0,
      form: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
          { code: 'A', title: '', img: '', isRight: true },
          { code: 'B', title: '', img: '', isRight: false },
          { code: 'C', title: '', img: '', isRight: false },
          { code: 'D', title: '', img: '', isRight: false }
        ], // 选项
        videoURL: '', // 视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: ''
      },
      value: '',

      // 单选、复选
      checkList: [],
      checkBoxList: [],
      arr: [],
      radioGroup: '1',

      rules: {
        subjectID: [
          { required: true, message: '请选择学科名称', trigger: 'blur' }
        ],
        catalogID: [
          { required: true, message: '请选择目录名称', trigger: 'blur' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业名称', trigger: 'blur' }
        ],
        city: [{ required: true, message: '请选择城市名称', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        answer: [{ required: true, message: '请选择企业名称', trigger: 'blur' }]
      },

      checkedIndex: 0,
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ script: 'sub' }, { script: 'super' }],
            [{ indent: '-1' }, { indent: '+1' }],
            [{ direction: 'rtl' }],
            [{ size: ['small', false, 'large', 'huge'] }],
            [{ header: [1, 2, 3, 4, 5, 6, false] }],
            [{ color: [] }, { background: [] }],
            [{ font: [] }],
            [{ align: [] }],
            ['clean'],
            ['link', 'image', 'video']
          ],
          syntax: {
            highlight: text => {
              return hljs.highlightAuto(text).value // 这里就是代码高亮需要配置的地方
            }
          }
        }
      }
    }
  },

  created () {
    this.getObjectList()
    this.getCompanysList()
    this.editQuestions()
  },

  methods: {
    async editQuestions () {
      if (this.queryId) {
        const res = await detail({
          id: this.queryId
        })
        this.number = res.data.number
        this.form = {
          ...res.data,
          difficulty: res.data.difficulty,
          questionType: res.data.questionType,
          tags: res.data.tags.split(',')
        }
        if (res.data.questionType === '2') {
          res.data.options
            .filter(item => item.isRight === 1)
            .forEach(item => {
              this.checkBoxList.push(item.code)
            })
        }
      }
    },

    async getObjectList () {
      const res = await list({
        pagesize: 100
      })
      this.companys = res.data.items
    },

    async getCompanysList () {
      const res = await SubApi.simple()
      this.subject = res.data
    },

    async getDirectorys () {
      this.form.catalogID = ''
      this.form.tags = ''
      const directorysRes = await simple({
        subjectID: this.form.subjectID
      })
      this.directorys = directorysRes.data
      const tagsRes = await tagsSimple({
        subjectID: this.form.subjectID
      })
      this.tags = tagsRes.data
    },

    onProvinceChange (val) {
      this.citys = citys(val)
    },

    // 图片上传
    onRequest (data) {
      cos.putObject(
        {
          Bucket: 'zsyt-1308960773' /* 必须 */,
          Region: 'ap-shanghai' /* 存储桶所在地域，必须字段 */,
          Key: data.file.name /* 必须 */,
          StorageClass: 'STANDARD',
          Body: data.file, // 上传文件对象
          onProgress: progressData => {}
        },
        (err, data) => {
          if (err) {
            console.log(err)
          }
          if (!err && data.statusCode === 200) {
            // this.form.options[index].img = 'https://' + data.Location
            this.form.options[this.checkedIndex].img =
              'https://' + data.Location
          }
        }
      )
    },

    addBtn () {
      this.form.options.push({
        code: String.fromCharCode(65 + this.form.options.length),
        title: '',
        isRight: false,
        img: ''
      })
    },

    radioChange (val) {
      this.form.options.forEach(item => {
        item.isRight = false
      })
      this.form.options[val - 1].isRight = true
    },

    typeChange (val) {
      this.form.questionType = val
      if (val === '2') {
        this.form.options = [
          { code: 'A', title: '', img: '', isRight: false },
          { code: 'B', title: '', img: '', isRight: false },
          { code: 'C', title: '', img: '', isRight: false },
          { code: 'D', title: '', img: '', isRight: false }
        ]
      }
    },

    async onSubmit () {
      await this.$refs.form.validate()
      if (this.queryId) {
        await update({
          id: this.queryId,
          ...this.form,
          difficulty: this.form.difficulty.toString(),
          questionType: this.form.questionType.toString(),
          tags: this.form.tags.join(',')
        })
        Message({
          type: 'success',
          message: '编辑成功'
        })
      } else {
        await add({
          subjectID: this.form.subjectID,
          catalogID: this.form.catalogID,
          enterpriseID: this.form.enterpriseID,
          province: this.form.province,
          city: this.form.city,
          direction: this.form.direction,
          questionType: this.form.questionType,
          difficulty: this.form.difficulty,
          question: this.form.question,
          options: this.form.options,
          videoURL: this.form.videoURL,
          answer: this.form.answer,
          remarks: this.form.remarks,
          tags: this.form.tags.join(',')
        })
        Message({
          type: 'success',
          message: '添加成功'
        })
      }
      this.$refs.form.resetFields()
      this.$router.push('/questions/list')
    },

    boxChange (val, index) {
      this.form.options[index].isRight = val
    }
  },

  computed: {
    provincesCity () {
      return provinces()
    },

    constantsList () {
      return direction
    }
  }
}
</script>

<style scoped lang="less">
.container {
  padding: 20px;
  .question-new-top {
    border-bottom: 1px solid #eee;
    font-weight: normal;
    font-size: 16px;
    margin: -20px;
    height: 56px;
    line-height: 56px;
    margin-bottom: 20px;
    text-indent: 2em;
  }
  .checkbox {
    display: flex;
    margin: 20px;
    width: 500px;
  }
}

::v-deep .avatar-uploader .el-upload {
  width: 102px;
  height: 70px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  margin-left: 10px;
  position: relative;
  overflow: hidden;
  img {
    width: 100%;
    height: 100%;
  }
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
.disabled .el-upload--picture-card {
  display: none;
}
</style>
